package org.example.gateway.spi.balancers;

import org.example.gateway.annoation.LoadBalance;
import org.example.gateway.contants.LoadBalanceConstants;
import org.example.gateway.pojo.dto.ServiceInstance;
import org.example.gateway.spi.LoadBalancer;

import java.util.List;

@LoadBalance(LoadBalanceConstants.WEIGHT_ROUND)
public class WeightRoundBalancer implements LoadBalancer {
    private volatile int index;

    @Override
    public synchronized ServiceInstance chooseOne(List<ServiceInstance> instances) {
        int allWeight = instances.stream().mapToInt(ServiceInstance::getWeight).sum();
        int number = (index++) % allWeight;
        for (ServiceInstance instance : instances) {
            if (instance.getWeight() > number) {
                return instance;
            }
            number -= instance.getWeight();
        }
        return null;
    }
}
